<template>
  <div>
  <!-- 父组件向子组件传值 -->
  <HomeHeader></HomeHeader>
  <HomeSwiper :list="swiperList"></HomeSwiper>
  <HomeIcons :list="iconList"></HomeIcons>
  <HomeRecommend :list="recommendList"></HomeRecommend>
  <HomeWeekend :list="weekendList"></HomeWeekend>
  </div>
</template>

<script>
import HomeHeader from './components/Header'
import HomeSwiper from './components/Swiper'
import HomeIcons from './components/Icons'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import axios from 'axios'
import { mapState } from 'vuex'

export default {
  name: 'Home',
  data () {
    return {
      // 保存上次城市
      lastCity: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },
  computed: {
    ...mapState(['city'])
  },
  methods: {
    // 获取ajax数据
    getHomeInfo () {
      // http//localhost:8088/public/data/index.json
      axios.get('/api/index.json?city=' + this.city).then(res => {
        this.getHomeInfoSucc(res)
      }).catch(function (error) { // 请求失败处理
        console.log(error)
      })
    },
    // 数据成功返回
    getHomeInfoSucc (res) {
      // res.data返回成功数据
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  // 页面初次挂载完成  ---生命周期钩子
  mounted () {
    // 渲染完毕让城市名保存至上一次
    this.lastCity = this.city
    // 生命周期函数中挂载获取数据方法
    this.getHomeInfo()
  },
  // keep-alive 执行的时候触发
  // 当页面重新显示的时候 ---生命周期钩子
  activated () {
    // 当前城市不等于上一次选择城市
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  }
}
</script>

<style>
</style>
